<template>
  <view class="follow-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="20"></u-icon>
        <text class="header-title">成员跟进</text>
      </view>
      <view class="group-name">{{ currentGroup.name }}</view>
    </view>

    <!-- 列表和添加按钮 -->
    <view class="list-header animate-card">
      <view class="list-title">
        <u-icon name="calendar" size="20" color="#007aff"></u-icon>
        <text>成员跟进记录</text>
        <text class="record-count" v-if="followList.length > 0">({{ followList.length }})</text>
      </view>
      <u-button type="primary" size="mini" shape="circle" icon="plus" @click="showAddModal">跟进</u-button>
    </view>

    <!-- 跟进记录列表 -->
    <view class="follow-list">
      <view
        class="follow-item animate-item"
        v-for="(item, index) in followList"
        :key="index"
        :style="{ animationDelay: index * 0.1 + 's' }"
      >
        <view class="follow-card">
          <view class="card-header">
            <view class="delivery-date">
              <u-icon name="calendar" size="16" color="#007aff"></u-icon>
              <text>递送时间: {{ item.deliveryDate }}</text>
            </view>
            <view class="action-buttons">
              <u-button type="primary" size="mini" @click="editFollow(index)" shape="circle">编辑</u-button>
              <u-button
                type="error"
                size="mini"
                @click="confirmDelete(index)"
                shape="circle"
                plain
              >删除</u-button>
            </view>
          </view>

          <view class="follow-content">
            <view class="content-item">
              <view class="item-label">递送方案:</view>
              <view class="item-value">{{ item.planName }}</view>
            </view>

            <view class="content-item">
              <view class="item-label">政策资费:</view>
              <view class="item-value">{{ item.policy }}</view>
            </view>

            <view class="content-item notes-item">
              <view class="item-label">跟进备注:</view>
              <view class="item-value notes-content">{{ item.notes || '无跟进备注' }}</view>
            </view>
          </view>

          <view class="card-footer">
            <view class="update-time">更新时间: {{ item.updateTime }}</view>
            <view class="operator">跟进人: {{ item.operator || '系统' }}</view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="followList.length === 0">
        <u-empty mode="data" text="暂无跟进记录，点击添加按钮新增" margin-top="60"></u-empty>
      </view>
    </view>

    <!-- 新增/编辑弹窗 -->
    <view class="custom-popup-mask" v-if="showPopup" @click.stop="onMaskClick">
      <view class="custom-popup-content" @click.stop>
        <view class="custom-popup-close" @click="onPopupClose">×</view>
        <view class="popup-content">
          <view class="popup-title">{{ isEdit ? '编辑跟进记录' : '新增跟进记录' }}</view>

          <view class="form-content">
            <view class="form-group">
              <view class="form-row">
                <view class="form-label">
                  递送时间
                  <text class="required">*</text>
                </view>
                <view class="form-control date-picker">
                  <picker
                    mode="date"
                    :value="formData.deliveryDate"
                    :end="getCurrentDate()"
                    @change="dateChange"
                  >
                    <view class="picker-value">
                      <text>{{ formData.deliveryDate || '请选择日期' }}</text>
                      <u-icon name="arrow-right" size="16" color="#c0c4cc"></u-icon>
                    </view>
                  </picker>
                </view>
              </view>
            </view>

            <view class="form-group">
              <view class="form-label">递送方案</view>
              <view class="form-control">
                <u-input
                  v-model="formData.planName"
                  placeholder="可选，请输入递送方案名称"
                  border="bottom"
                  clearable
                />
              </view>
            </view>

            <view class="form-group">
              <view class="form-label">政策资费</view>
              <view class="form-control">
                <u-input
                  v-model="formData.policy"
                  placeholder="可选，请输入政策资费内容"
                  border="bottom"
                  clearable
                />
              </view>
            </view>

            <view class="form-group">
              <view class="form-label">
                跟进备注
                <text class="required">*</text>
              </view>
              <view class="form-control">
                <u-textarea
                  v-model="formData.notes"
                  placeholder="请输入跟进备注内容，例如：8月7日，拜访客户单位XXX，沟通了XX产品的报价及设计方案，XX意向8月份建设..."
                  height="100"
                  count
                  maxlength="300"
                ></u-textarea>
              </view>
            </view>
          </view>

          <view class="popup-footer">
            <u-button type="default" shape="circle" @click="showPopup = false" :plain="true">取消</u-button>
            <u-button
              type="primary"
              shape="circle"
              @click="saveFollow"
              :loading="loading"
            >{{ isEdit ? '保存修改' : '确认添加' }}</u-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 自定义确认弹窗 -->
    <view class="custom-modal-mask" v-if="showDeleteModal" @click.stop="cancelDelete">
      <view class="custom-modal-content" @click.stop>
        <view class="custom-modal-title">确认删除</view>
        <view class="custom-modal-text">是否确认删除该跟进记录？删除后无法恢复。</view>
        <view class="custom-modal-btns">
          <view class="custom-modal-btn cancel-btn" @click="cancelDelete">取消</view>
          <view class="custom-modal-btn confirm-btn" @click="deleteFollow">确认删除</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      groupId: "",
      currentGroup: {},
      followList: [],
      showPopup: false,
      showDeleteModal: false,
      isEdit: false,
      currentIndex: -1,
      loading: false,
      formData: {
        id: "",
        deliveryDate: "",
        planName: "",
        policy: "",
        notes: "",
        updateTime: "",
        operator: ""
      }
    };
  },
  onLoad(options) {
    if (options && options.groupCode) {
      this.groupId = options.groupCode;
      this.getGroupInfo();
      this.getFollowList();
    } else if (options && options.groupId) {
      this.groupId = options.groupId;
      this.getGroupInfo();
      this.getFollowList();
    } else {
      this.goBack();
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 获取集团信息
    getGroupInfo() {
      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 尝试从API获取集团信息
      this.$http
        .sendRequest("zhanke/group_detail", "POST", {
          groupCode: this.groupId
        })
        .then(res => {
          uni.hideLoading();

          if (res.data && res.data.code === 200) {
            const detail = res.data.data;
            // 设置当前集团信息
            this.currentGroup = {
              name: detail.name,
              code: detail.code,
              industry: detail.industry,
              district: detail.district,
              manager: detail.manager,
              managerPhone: detail.managerPhone
            };
          } else {
            // API请求失败，尝试从缓存获取
            this.getGroupInfoFromStorage();
          }
        })
        .catch(err => {
          uni.hideLoading();
          // API请求错误，尝试从缓存获取
          this.getGroupInfoFromStorage();
        });
    },

    // 从本地存储获取集团信息
    getGroupInfoFromStorage() {
      try {
        // 从本地存储获取
        const groupOptions = uni.getStorageSync("groupOptions");
        if (groupOptions) {
          const groups = JSON.parse(groupOptions);
          // 注意这里使用code字段匹配，因为groupId实际上存储的是集团的code
          const group = groups.find(item => item.code === this.groupId);
          if (group) {
            this.currentGroup = group;
            return;
          }
        }

        // 如果没有找到匹配的数据，使用默认数据
        this.currentGroup = {
          name: "未知集团单位",
          industry: "未分类"
        };

        // 显示提示
        uni.showToast({
          title: "获取集团信息失败",
          icon: "none"
        });
      } catch (e) {
        // 使用默认数据
        this.currentGroup = {
          name: "未知集团单位",
          industry: "未分类"
        };
      }
    },

    // 获取跟进记录列表
    getFollowList() {
      // 显示加载提示
      uni.showLoading({
        title: "加载中..."
      });

      // 从API获取数据
      this.$http
        .sendRequest("zhanke/member_follow_list", "POST", {
          groupCode: this.groupId,
          page: 1,
          limit: 50
        })
        .then(res => {
          uni.hideLoading();

          if (res.data && res.data.code === 200) {
            const list = res.data.data.list || [];

            // 将API返回的数据格式化为组件需要的格式
            this.followList = list.map(item => {
              return {
                id: item.id,
                deliveryDate: item.deliveryDate,
                planName: item.planName || "常规计划",
                policy: item.deliveryPolicy || "",
                notes: item.notes || "", // 确保notes字段有值，即使API返回为空
                updateTime: item.createTime, // 直接使用API返回的createTime作为更新时间
                operator: item.manager
              };
            });

            // 保存到本地缓存
            this.saveFollowList();
          } else {
            // API请求失败，尝试从本地存储获取
            this.getFollowListFromStorage();

            uni.showToast({
              title: res.data.msg || "获取跟进记录失败",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          // API请求错误，尝试从本地存储获取
          this.getFollowListFromStorage();

          uni.showToast({
            title: "网络请求失败，显示本地数据",
            icon: "none"
          });
        });
    },

    // 从本地存储获取跟进记录
    getFollowListFromStorage() {
      try {
        const followListStr = uni.getStorageSync("followList_" + this.groupId);
        if (followListStr) {
          this.followList = JSON.parse(followListStr);
        } else {
          // 如果没有本地数据，显示空列表
          this.followList = [];
        }
      } catch (e) {
        this.followList = [];
      }
    },

    // 显示添加弹窗
    showAddModal() {
      this.isEdit = false;
      this.currentIndex = -1;
      this.resetForm();
      // 直接打开弹窗
      this.showPopup = true;
    },

    // 编辑跟进记录
    editFollow(index) {
      this.isEdit = true;
      this.currentIndex = index;

      // 复制一份数据，避免直接修改列表数据
      this.formData = JSON.parse(JSON.stringify(this.followList[index]));

      // 验证递送日期是否合法（不超过当前日期）
      if (this.isDateAfterToday(this.formData.deliveryDate)) {
        // 如果日期超过当前日期，将其设置为当前日期
        this.formData.deliveryDate = this.getCurrentDate();
        uni.showToast({
          title: "递送时间已自动调整为今天",
          icon: "none",
          duration: 2000
        });
      }

      // 打开弹窗
      this.showPopup = true;
    },

    // 确认删除
    confirmDelete(index) {
      this.currentIndex = index;
      // 直接打开弹窗
      this.showDeleteModal = true;
    },

    // 删除跟进记录
    deleteFollow() {
      if (
        this.currentIndex < 0 ||
        this.currentIndex >= this.followList.length
      ) {
        return;
      }

      const followId = this.followList[this.currentIndex].id;

      // 开始删除
      uni.showLoading({
        title: "删除中..."
      });

      // 调用API删除数据
      this.$http
        .sendRequest("zhanke/member_follow_delete", "POST", {
          id: followId
        })
        .then(res => {
          uni.hideLoading();

          if (res.data && res.data.code === 200) {
            // 从列表中移除
            this.followList.splice(this.currentIndex, 1);

            // 保存更新后的列表到本地
            this.saveFollowList();

            // 关闭删除确认框
            this.showDeleteModal = false;

            uni.showToast({
              title: "删除成功",
              icon: "success"
            });
          } else {
            uni.showToast({
              title: res.data.msg || "删除失败",
              icon: "none"
            });
          }
        })
        .catch(err => {
          uni.hideLoading();
          // API删除失败，尝试只在本地删除
          this.deleteLocalOnly();
        });
    },

    // 仅在本地删除
    deleteLocalOnly() {
      // 从列表中移除
      this.followList.splice(this.currentIndex, 1);

      // 保存更新后的列表
      this.saveFollowList();

      // 关闭删除确认框
      this.showDeleteModal = false;

      uni.showToast({
        title: "本地删除成功",
        icon: "success"
      });
    },

    // 日期选择变更
    dateChange(e) {
      const selectedDate = e.detail.value;

      // 检查选择的日期是否超过当前日期
      if (this.isDateAfterToday(selectedDate)) {
        uni.showToast({
          title: "递送时间不能超过当前日期",
          icon: "none"
        });
        return;
      }

      this.formData.deliveryDate = selectedDate;
    },

    // 检查日期是否超过今天
    isDateAfterToday(dateStr) {
      const today = new Date();
      today.setHours(0, 0, 0, 0); // 设置时间为当天的00:00:00

      const selectedDate = new Date(dateStr);
      selectedDate.setHours(0, 0, 0, 0);

      return selectedDate > today;
    },

    // 重置表单
    resetForm() {
      this.formData = {
        id: "",
        deliveryDate: this.getCurrentDate(),
        planName: "",
        policy: "",
        notes: "",
        updateTime: "",
        operator: "" // 使用API返回的当前用户
      };
    },

    // 保存跟进记录
    saveFollow() {
      // 表单验证
      if (!this.formData.deliveryDate) {
        uni.showToast({
          title: "请选择递送时间",
          icon: "none"
        });
        return;
      }

      // 检查递送时间是否超过当前日期
      if (this.isDateAfterToday(this.formData.deliveryDate)) {
        uni.showToast({
          title: "递送时间不能超过当前日期",
          icon: "none"
        });
        return;
      }

      // 递送方案和政策资费可以为空

      // 验证跟进备注不能为空
      if (!this.formData.notes || this.formData.notes.trim() === "") {
        uni.showToast({
          title: "请输入跟进备注",
          icon: "none"
        });
        return;
      }

      // 开始保存
      this.loading = true;

      // 构建API请求参数
      const params = {
        groupCode: this.groupId,
        deliveryDate: this.formData.deliveryDate,
        planName: this.formData.planName,
        deliveryPolicy: this.formData.policy,
        notes: this.formData.notes || "" // 确保传递notes字段
      };

      // 如果是编辑模式，添加ID参数
      if (this.isEdit && this.formData.id) {
        params.id = this.formData.id;
      }

      // 根据是否为编辑模式选择不同的API
      const apiUrl = this.isEdit
        ? "zhanke/member_follow_update"
        : "zhanke/member_follow_add";

      // 调用API保存数据
      this.$http
        .sendRequest(apiUrl, "POST", params)
        .then(res => {
          this.loading = false;

          if (res.data && res.data.code === 200) {
            // API保存成功
            // 更新本地数据
            this.updateLocalData(res.data.data.id);

            // 关闭弹窗
            this.showPopup = false;

            // 显示成功提示
            setTimeout(() => {
              uni.showToast({
                title: this.isEdit ? "修改成功" : "添加成功",
                icon: "success"
              });
            }, 300);
          } else {
            // API保存失败
            uni.showToast({
              title: res.data.msg || (this.isEdit ? "修改失败" : "添加失败"),
              icon: "none"
            });
          }
        })
        .catch(err => {
          this.loading = false;
          // API保存失败，尝试只保存到本地
          this.saveToLocalOnly();

          uni.showToast({
            title: "网络请求失败，已保存到本地",
            icon: "none"
          });
        });
    },

    // 更新本地数据
    updateLocalData(newId) {
      // 不修改原始updateTime，直接使用API返回的时间
      if (!this.formData.updateTime || this.formData.updateTime === "") {
        this.formData.updateTime = this.getFormattedDateTime();
      }

      if (this.isEdit) {
        // 编辑模式，更新列表中的数据
        this.followList[this.currentIndex] = JSON.parse(
          JSON.stringify(this.formData)
        );
      } else {
        // 新增模式
        // 使用API返回的ID或生成本地ID
        this.formData.id = newId || "follow_" + this.groupId + "_" + Date.now();
        // 添加到列表
        this.followList.unshift(JSON.parse(JSON.stringify(this.formData)));
      }

      // 保存更新后的列表到本地存储
      this.saveFollowList();
    },

    // 仅保存到本地
    saveToLocalOnly() {
      // 仅当没有updateTime时设置当前时间
      if (!this.formData.updateTime || this.formData.updateTime === "") {
        this.formData.updateTime = this.getFormattedDateTime();
      }

      if (this.isEdit) {
        // 编辑模式，更新列表中的数据
        this.followList[this.currentIndex] = JSON.parse(
          JSON.stringify(this.formData)
        );
      } else {
        // 新增模式，生成本地ID
        this.formData.id = "follow_" + this.groupId + "_" + Date.now();
        // 添加到列表
        this.followList.unshift(JSON.parse(JSON.stringify(this.formData)));
      }

      // 保存更新后的列表到本地存储
      this.saveFollowList();

      // 关闭弹窗
      this.showPopup = false;

      // 显示成功提示
      setTimeout(() => {
        uni.showToast({
          title: this.isEdit ? "本地修改成功" : "本地添加成功",
          icon: "success"
        });
      }, 300);
    },

    // 保存跟进记录列表到本地存储
    saveFollowList() {
      try {
        uni.setStorageSync(
          "followList_" + this.groupId,
          JSON.stringify(this.followList)
        );
      } catch (e) {
        // 存储失败处理
      }
    },

    // 获取当前日期，格式为YYYY-MM-DD
    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 获取格式化的日期时间，格式为YYYY-MM-DD HH:MM:SS
    getFormattedDateTime() {
      const date = new Date();

      // 获取年月日时分秒并进行补零处理
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      // 按照YYYY-MM-DD HH:MM:SS格式返回
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 新增方法：弹窗关闭回调
    onPopupClose() {
      this.showPopup = false;
      this.resetForm();
    },

    // 新增方法：取消删除
    cancelDelete() {
      this.showDeleteModal = false;
      this.currentIndex = -1;
    },

    // 新增方法：遮罩点击回调
    onMaskClick() {
      // 点击遮罩关闭弹窗
      this.showPopup = false;
    }
  }
};
</script>

<style>
.follow-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 30px;
}

.page-header {
  background: linear-gradient(120deg, #007aff, #0056b3);
  padding: 60px 20px 25px;
  color: #ffffff;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
  margin-left: 5px;
}

.group-name {
  font-size: 14px;
  opacity: 0.8;
  margin-top: 8px;
}

.animate-card {
  animation: slideUp 0.5s ease-out;
  transition: all 0.3s ease;
}

@keyframes slideUp {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.list-header {
  margin: 15px;
  padding: 15px 20px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 3px 15px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  flex: 0 0 auto;
  width: 55%;
}

.list-title text {
  margin-left: 8px;
}

.record-count {
  font-size: 14px;
  color: #909399;
  font-weight: normal;
  margin-left: 5px;
}

.list-header u-button {
  margin-left: auto;
}

.follow-list {
  padding: 0 15px;
}

.animate-item {
  animation: slideUp 0.5s ease-out;
  transition: all 0.3s ease;
}

.follow-item {
  margin-bottom: 15px;
}

.follow-card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 3px 15px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
}

.follow-card:active {
  transform: scale(0.98);
}

.card-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f2f3f5;
}

.delivery-date {
  display: flex;
  align-items: center;
  font-size: 15px;
  color: #333;
  font-weight: bold;
}

.delivery-date u-icon {
  margin-right: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.follow-content {
  padding: 15px;
}

.content-item {
  margin-bottom: 12px;
}

.content-item:last-child {
  margin-bottom: 0;
}

.item-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.item-value {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.notes-item {
  margin-top: 15px;
}

.notes-content {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 8px;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.card-footer {
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  background-color: #f8f9fa;
  font-size: 12px;
  color: #909399;
}

.empty-state {
  margin-top: 20px;
}

.popup-content {
  padding: 25px;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 25px;
  text-align: center;
}

.form-content {
  margin-bottom: 25px;
}

.form-group {
  margin-bottom: 18px;
}

.form-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.form-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.form-row .form-label {
  margin-bottom: 0;
  margin-right: 10px;
  flex-shrink: 0;
  width: 80px;
}

.form-control {
  position: relative;
}

.form-row .form-control {
  flex: 1;
}

.date-picker {
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
}

.form-row .date-picker {
  flex: 1;
}

.picker-value {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #333;
  height: 24px;
  width: 100%;
  padding: 0 2px;
}

.picker-value text {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.popup-footer {
  display: flex;
  justify-content: space-between;
  gap: 15px;
}

.popup-footer u-button {
  flex: 1;
}

.u-button {
  margin-left: auto;
}

.custom-popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.custom-popup-content {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 16px;
  width: 90%;
  max-width: 400px;
  position: relative;
}

.custom-popup-close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 20px;
  color: #909399;
  cursor: pointer;
}

.custom-modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.custom-modal-content {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 16px;
  width: 90%;
  max-width: 400px;
  position: relative;
}

.custom-modal-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.custom-modal-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 20px;
  text-align: center;
}

.custom-modal-btns {
  display: flex;
  justify-content: space-between;
}

.custom-modal-btn {
  flex: 1;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  text-align: center;
  margin: 0 10px;
}

.cancel-btn {
  background-color: #f8f8f8;
  color: #666666;
}

.confirm-btn {
  background-color: #007aff;
  color: #ffffff;
}

.required {
  color: #f56c6c;
  margin-left: 4px;
  font-size: 14px;
  vertical-align: middle;
}
</style> 